import React, { useEffect, useState } from 'react'
import { Menu } from "antd"
import menusConfig from "../config/menuConfig"
import {useDispatch} from "react-redux"
import {menuPushAC} from "../redux/actions/menuAction"

export default function MyMenu() {
    const [userInfo,setUseInfo] = useState({role:{}})
    const dispatch = useDispatch()
    useEffect(()=>{
        const info = JSON.parse(localStorage.userInfo || "{role:{}}")
        setUseInfo(info)
    },[])

    //对menusConfig的数据进行筛选，得到满足条件的数据。在渲染
    // array代表你要筛选的菜单数组，news代表筛选完了保存起来数组
    const deepMenus2 = (array,news = [])=>{
        //userInfo = {role:{menus:["/home/","/home/user"]}}
        const {menus=[]} = userInfo.role
        for (const item of array) {
            if(menus.includes(item.key)){
                news.push(item)
            }
        }
        return news
    }
    const deepMenus = (array,news = [])=>{
        //userInfo = {role:{menus:["/home/","/home/user"]}}
        const {menus=[]} = userInfo.role
        for (const item of array) {
            if(!item.children){
                if(menus.includes(item.key)){
                    news.push(item)
                }
            }else{ //发现当前这个菜单有子菜单
                let node = {...item,children:[]}
                deepMenus(item.children,node.children)
                if(node.children.length != 0){
                     news.push(node)
                }
            }
        }
        return news
    }
    
    const checkedMenu = ({item,key,keyPath,domEvent})=>{
        const menuName = domEvent.target.innerText;
        let menu = {
            title:menuName,
            path:key,
            status:true
        }
        dispatch(menuPushAC(menu))

    }
    return (
        <Menu
            theme="dark"
            defaultSelectedKeys={['/home/']}
            defaultOpenKeys={["/home/product","/home/chart"]}
            mode="inline"
            onClick={checkedMenu}
            items={deepMenus(menusConfig)}
        />
    )
}
